package com.chen.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.service.IAccount;
import com.chen.entity.Account;
import com.chen.mapper.AccountMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.dromara.hmily.common.exception.HmilyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
@Slf4j
public class AccountImpl extends ServiceImpl<AccountMapper, Account> implements IAccount {
    @Resource
    private AccountMapper accountMapper;

    @Override
    @HmilyTCC(confirmMethod = "commitTransfer",cancelMethod = "cancelTransfer")
    @Transactional(rollbackFor = HmilyException.class)
    public void transferInto(int accountId, BigDecimal amount) throws HmilyException {
        // 检查数据合法性
        Account account = getById(accountId);
        if (account == null){
            throw new HmilyException("转入账户不存在");
        }
        account.setFrozenAmount(amount);
        updateById(account);
    }

    @Override
    public void transferOut(int accountId, BigDecimal amount) throws Exception {

    }

    @Override
    @HmilyTCC(confirmMethod = "commitTransfer",cancelMethod = "cancelTransfer")
    @Transactional(rollbackFor = Exception.class)
    public void transferIntoWithException(int accountId, BigDecimal amount) throws HmilyException {
        // 检查数据合法性
        Account account = getById(accountId);
        if (account == null){
            throw new HmilyException("转入账户不存在");
        }
        account.setFrozenAmount(amount);
        updateById(account);
        System.out.println(3/0);
        System.out.println("跳过异常。。。。。。。。。。");

    }


    public void commitTransfer(int accountId, BigDecimal amount) throws HmilyException{
        log.info("执行service2-commit");
        accountMapper.transferIn(accountId,amount);
    }

    public void cancelTransfer(int accountId, BigDecimal amount) throws HmilyException{
        log.error("执行service2-cancel");
        accountMapper.unFreezeAmount2(accountId,amount);
    }

/*    @Override
    public void transferInto(int accountId, BigDecimal amount) throws Exception {
        Account account = this.getById(accountId);
        if (account == null){
            throw new Exception("目标账户不存在");
        }
        account.setAmount(account.getAmount().add(amount));
        this.updateById(account);
    }

    @Override
    public void transferOut(int accountId, BigDecimal amount) throws Exception {
        Account account = this.getById(accountId);
        if (account == null){
            throw new Exception("待转出账户不存在");
        }
        if (account.getAmount().compareTo(amount) == -1 ){
            throw new Exception("账户余额不足");
        }
        account.setAmount(account.getAmount().subtract(amount));
        this.updateById(account);
    }*/


}
